﻿using Elasticsearch.Net;
using Nest;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Dynamic;
using System.Linq;
using System.Text;
using ZYHand.DTO;
using ZYHand.Entity;
using ZYHand.IRepository;

namespace ZYHand.Repository
{
   public class ElasticSearchRepository: IElasticSearchRepository
    {
        /// <summary>
        /// 强类型存入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="index"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool Post<T>(string index,T data) where T : class, new()
        {
            var client = ElasticSearchClient.GetInstance(index).Client(); // 
            Result result = Result.NotFound;

            result = client.Index<T>(data, idx => idx.Index(index)).Result;  //如未创建索引 ，会自动创建索引

            if (result == Result.Created || result == Result.Updated)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 使用ExpandoObject对象来存入随意字段
        /// </summary>
        /// <param name="index"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool PostByString(string index, ExpandoObject data)
        {
            var client = ElasticSearchClient.GetInstance(index).Client(); // 
            Result result = Result.NotFound;

            result = client.IndexDocument(data).Result;  //如未创建索引 ，会自动创建索引

            if (result == Result.Created || result == Result.Updated)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 全字段匹配搜索
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keywords"></param>
        /// <param name="index">索引名称</param>
        /// <param name="from"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public SearchData<T> Match<T>(string keywords,string index="order",int from=1,int size=10)
        {
            var client = ElasticSearchClient.GetInstance(index).Client();
            var modList = client.Search<Order>(s => s
                .From(from)
                .Size(size)
                .Query(q => q.MultiMatch(m=>m.Query(keywords)))
            );

            SearchData<T> data = new SearchData<T>();
            data.Count = modList.Total;
            data.Keywords = keywords;
            data.From = from;
            data.Size = size;
            data.DataList = modList.Documents.ToList()  as IList<T>;

            return data;
        }
    }
}
